package org.cyhz.util;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.cyhz.domain.TimeWindow;

public class TimeWindowUtil {

	private static TimeWindow getPreviousTimeWindow(Date enddate,
			int timeWindowWidth) {

		Calendar start = Calendar.getInstance();
		start.setTime(enddate);
		start.add(Calendar.DAY_OF_MONTH, 1 - (timeWindowWidth));

		return new TimeWindow(getFirstSecondOfDay(start.getTime()),
				getLastSecondOfDay(enddate));
	}

	private static TimeWindow getSubsequenceTimeWindow(Date startDate,
			int timeWindowWidth) {

		Calendar end = Calendar.getInstance();
		end.setTime(startDate);
		end.add(Calendar.DAY_OF_MONTH, timeWindowWidth - 1);

		return new TimeWindow(getFirstSecondOfDay(startDate),
				getLastSecondOfDay(end.getTime()));
	}

	private static Date addDays(Date d, int days) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.DAY_OF_MONTH, days);
		return c.getTime();
	}

	public static List<TimeWindow> getRollingTimeWindows(Date start,
			Date endDate, int timeWindowWidth) throws ParseException {
		List<TimeWindow> tws = new ArrayList<TimeWindow>();

		while (start.before(endDate)) {
			TimeWindow ts = getPreviousTimeWindow(start, timeWindowWidth);
			Log.debug(ts.toString());
			tws.add(ts);
			start = addDays(start, 1);
		}
		return tws;
	}

	public static Date getLastSecondOfDay(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR_OF_DAY, 23);
		c.set(Calendar.MINUTE, 59);
		c.set(Calendar.SECOND, 59);
		return c.getTime();
	}

	public static Date getFirstSecondOfDay(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		return c.getTime();
	}

	public static List<TimeWindow> getContiguousTimeWindows(Date start,
			Date endDate, int timeWindowWidth) throws ParseException {
		List<TimeWindow> tws = new ArrayList<TimeWindow>();
		while (start.before(endDate)) {
			TimeWindow ts = getSubsequenceTimeWindow(start, timeWindowWidth);
			if (endDate.before(ts.getEndDate())) {
				ts.setEndDate(getLastSecondOfDay(endDate));
				Log.debug(ts.toString());
				tws.add(ts);
				break;
			}
			Log.debug(ts.toString());
			tws.add(ts);
			start = addDays(start, timeWindowWidth);
		}
		return tws;
	}

	public static void main(String[] args) throws ParseException {
		Calendar s = Calendar.getInstance();
		s.set(2013, 10, 10);
		Calendar e = Calendar.getInstance();
		e.set(2013, 11, 10);
		getContiguousTimeWindows(s.getTime(), e.getTime(), 3);
	}

}
